﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Magicodes.WeiChat.Infrastructure.MvcExtension.Ajax;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
using Magicodes.WeiChat.Data;
using Magicodes.WeiChat.Data.Models;
using Magicodes.WeChat.SDK;
using Magicodes.WeiChat.Models;
using Magicodes.WeiChat.WeChatHelper.Task;
using Magicodes.WeiChat.Helpers;
using Magicodes.WeiChat.Infrastructure.MvcExtension.Results;
using NLog;

namespace Magicodes.WeiChat.Controllers.WeChat.UsersAndGroups
{
    public class WeiChat_UserController : TenantBaseController<WeiChat_User>
    {
        // GET: WeiChat_User
        public async Task<ActionResult> Index(string q, int pageIndex = 1, int pageSize = 10, ExportTypes exportType = ExportTypes.None)
        {
            var queryable = db.WeiChat_Users.AsQueryable();
            if (!string.IsNullOrWhiteSpace(q))
            {
                //请替换为相应的搜索逻辑
                queryable = queryable.Where(p => p.NickName.Contains(q) || p.City.Contains(q) || p.Country.Contains(q) || p.Province.Contains(q) || p.Remark.Contains(q));
            }
            queryable = queryable.OrderByDescending(p => p.SubscribeTime);
            switch (exportType)
            {
                case ExportTypes.Csv:
                    return Csv(queryable.ToList());
                    //case Helpers.ExportTypes.Excel:
                    //    return Excel(queryable.ToList());

            }
            var pagedList = new PagedList<WeiChat_User>(
                             await queryable
                             .Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync(),
                             pageIndex, pageSize, await queryable.CountAsync());
            var myGroups = db.WeiChat_UserGroups.Where(p => p.TenantId == TenantId).ToList();
            foreach (var item in pagedList)
            {
                item.UserGroup = myGroups.FirstOrDefault(p => p.GroupId == item.GroupId);
            }
            ViewBag.UserGroups = new SelectList(myGroups, "GroupId", "Name");
            return View(pagedList);
        }

        public ActionResult IndexView(string q, int pageIndex = 1, int pageSize = 12, int? groupId = null)
        {
            var queryable = db.WeiChat_Users.AsQueryable();
            if (!string.IsNullOrWhiteSpace(q))
                queryable =
                    queryable.Where(
                        p =>
                            p.NickName.Contains(q) || p.City.Contains(q) || p.Country.Contains(q) ||
                            p.Province.Contains(q) || p.Remark.Contains(q));
            if (groupId != null)
                queryable = queryable.Where(p => p.GroupId == groupId);
            var pagedList = new PagedList<WeiChat_User>(
                queryable
                    .OrderByDescending(p => p.SubscribeTime)
                    .Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(),
                pageIndex, pageSize, queryable.Count());
            var myGroups = db.WeiChat_UserGroups.Where(p => p.TenantId == TenantId).ToList();
            ViewBag.UserGroups = new SelectList(myGroups, "GroupId", "Name");
            return View(pagedList);
        }

        // GET: WeiChat_User/Details/5
        public async Task<ActionResult> Details(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            WeiChat_User weiChat_User = await db.WeiChat_Users.FindAsync(id);
            if (weiChat_User == null)
            {
                return HttpNotFound();
            }
            return View(weiChat_User);
        }
        
        // GET: WeiChat_User/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: WeiChat_User/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "OpenId,Subscribe,NickName,Sex,City,Country,Province,Language,HeadImgUrl,SubscribeTime,UnionId,Remark,GroupId,AllowTest")] WeiChat_User weiChat_User)
        {
            if (ModelState.IsValid)
            {
                db.WeiChat_Users.Add(weiChat_User);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }

            return View(weiChat_User);
        }

        // GET: WeiChat_User/Edit/5
        public async Task<ActionResult> Edit(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            WeiChat_User weiChat_User = await db.WeiChat_Users.FirstOrDefaultAsync(p => p.OpenId == id);
            if (weiChat_User == null)
            {
                return HttpNotFound();
            }
            weiChat_User.UserGroup = db.WeiChat_UserGroups.FirstOrDefault(p => p.GroupId == weiChat_User.GroupId);
            return View(weiChat_User);
        }

        // POST: WeiChat_User/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit([Bind(Include = "OpenId,Subscribe,NickName,Sex,City,Country,Province,Language,HeadImgUrl,SubscribeTime,UnionId,Remark,GroupId,AllowTest")] WeiChat_User weiChat_User)
        {
            if (ModelState.IsValid)
            {
                var result = WeChatApisContext.Current.UserApi.SetRemark(weiChat_User.OpenId, weiChat_User.Remark);
                if (result.IsSuccess())
                {
                    var model = await db.WeiChat_Users.FindAsync(weiChat_User.OpenId);
                    model.Remark = weiChat_User.Remark;
                    await db.SaveChangesAsync();
                    return RedirectToAction("Index");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, result.GetFriendlyMessage());
                }
            }
            weiChat_User.UserGroup = db.WeiChat_UserGroups.FirstOrDefault(p => p.GroupId == weiChat_User.GroupId);
            return View(weiChat_User);
        }

        // GET: WeiChat_User/Delete/5
        public async Task<ActionResult> Delete(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            WeiChat_User weiChat_User = await db.WeiChat_Users.FindAsync(id);
            if (weiChat_User == null)
            {
                return HttpNotFound();
            }
            return View(weiChat_User);
        }

        // POST: WeiChat_User/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteConfirmed(string id)
        {
            WeiChat_User weiChat_User = await db.WeiChat_Users.FindAsync(id);
            db.WeiChat_Users.Remove(weiChat_User);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        // POST: WeiChat_User/BatchOperation/{operation}
        /// <summary>
        /// 批量操作
        /// </summary>
        /// <param name="operation">操作方法</param>
        /// <param name="ids">主键集合</param>
        /// <returns></returns>
        [HttpPost]
        [Route("WeiChat_User/BatchOperation/{operation}")]
        public async Task<ActionResult> BatchOperation(string operation, int groupId, params string[] ids)
        {
            var ajaxResponse = new AjaxResponse();
            if (ids.Length > 0)
            {
                try
                {
                    var models = await db.WeiChat_Users.Where(p => ids.Contains(p.OpenId)).ToListAsync();
                    if (models.Count == 0)
                    {
                        ajaxResponse.Success = false;
                        ajaxResponse.Message = "没有找到匹配的项，项已被删除或不存在！";
                        return Json(ajaxResponse);
                    }
                    switch (operation.ToUpper())
                    {
                        case "MOVE":
                            #region 移动
                            {
                                var result = WeChatApisContext.Current.UserGroupApi.MemeberUpdate(ids, groupId);
                                if (result.IsSuccess())
                                {
                                    foreach (var item in models)
                                    {
                                        item.GroupId = groupId;
                                    }
                                    await db.SaveChangesAsync();
                                    ajaxResponse.Success = true;
                                    ajaxResponse.Message = string.Format("已成功操作{0}项！", models.Count);
                                }
                                else
                                {
                                    ajaxResponse.Success = false;
                                    ajaxResponse.Message = result.GetFriendlyMessage();
                                }
                                break;
                            }
                        #endregion
                        default:
                            break;
                    }
                }
                catch (Exception ex)
                {
                    ajaxResponse.Success = false;
                    ajaxResponse.Message = ex.Message;
                }
            }
            else
            {
                ajaxResponse.Success = false;
                ajaxResponse.Message = "请至少选择一项！";
            }
            return Json(ajaxResponse);
        }

        [HttpPost]
        public ActionResult SetRemark(string openId, string remark)
        {
            var ajaxResponse = new AjaxResponse();
            var user = db.WeiChat_Users.FirstOrDefault(p => p.OpenId == openId);
            if (user != null)
            {
                var result = WeChatApisContext.Current.UserApi.SetRemark(openId, remark);
                if (result.IsSuccess())
                {
                    user.Remark = remark;
                    db.SaveChanges();
                    ajaxResponse.Success = true;
                    ajaxResponse.Message = "操作成功";
                }
                else
                {
                    ajaxResponse.Success = false;
                    ajaxResponse.Message = result.GetFriendlyMessage();
                }
            }
            else
            {
                ajaxResponse.Success = false;
                ajaxResponse.Message = "账号不存在！";
            }
            return Json(ajaxResponse);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
